<template>
  <div class="container">
    <div class="section">
      <h3 class="section-title">开始面试</h3>

      <div class="input-group">
        <label>面试岗位：</label>
        <input
          v-model="job_position"
          type="text"
          class="vue-input"
          placeholder="输入面试岗位"
        />
      </div>

      <button class="vue-button primary" @click="startInterview">开始面试</button>

      <!-- 全部题目展示区域 -->
      <div v-if="questions.length" class="questions-list">
        <div
          v-for="(question, index) in questions"
          :key="index"
          class="question-card"
          :class="{ completed: completedQuestions.has(question.id) }"
        >
          <div class="question-content">
            <h4 class="question-title">题目 {{ index + 1 }}</h4>
            <p class="question-text">{{ question.context }}</p>
            <p class="question-meta">
              <span>题型：{{ question.type }}</span>
              <span>分值：{{ question.score }}分</span>
              <!-- 更新完成状态显示 -->
              <span v-if="question.completed" class="completed-status"> 已完成 </span>
            </p>
          </div>
          <button
            class="vue-button success"
            @click="handleAnswer(question)"
            :disabled="question.completed"
          >
            {{ question.completed ? "已完成" : "回答本题" }}
          </button>
        </div>
      </div>

      <!-- 添加提交按钮 -->
      <button
        v-if="questions.length > 0"
        class="vue-button submit"
        @click="showSubmitConfirmation"
      >
        提交面试
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from "vue";

// 监听题目完成事件
const onQuestionCompleted = (data) => {
  // 找到对应题目并更新完成状态
  const index = questions.value.findIndex((q) => q.id === data.questionId);
  if (index !== -1) {
    questions.value[index].completed = true;
    console.log(`题目 ${data.questionId} 已完成`);
  }

  // 检查是否所有题目都已完成
  if (questions.value.length > 0 && questions.value.every((q) => q.completed)) {
    console.log("所有题目已完成，跳转到overview页面");
    uni.navigateTo({
      url: "/pages/index/overview",
    });
  }
};

const props = defineProps({
  fileids: String,
  resume_id: String, // 新增接收 resume_id
});

const job_position = ref("后端JAVA开发");
const type = ref(123);
const questions = ref([]); // 改为数组存储所有题目
const completedQuestions = ref(new Set()); // 存储已完成题目的ID
let ws = null;

const showSubmitConfirmation = () => {
  uni.showModal({
    title: "提交确认",
    content: "请检查问题是否完成",
    confirmText: "确认提交",
    cancelText: "取消",
    success: (res) => {
      if (res.confirm) {
        // 跳转到overview页面并传递参数
        uni.navigateTo({
          url: `/pages/index/overview?fileids=${
            props.fileids
          }&interview_id=${uni.getStorageSync("current_interview_id")}`,
        });
      }
    },
  });
};

const startInterview = () => {
  const token = uni.getStorageSync("access_token");

  ws = new WebSocket(
    `ws://localhost:8085/chat?fileids=${props.fileids}&type=${type.value}&job_position=${job_position.value}`
  );

  ws.onopen = () => {
    ws.send(
      JSON.stringify({
        token,
        resume_id: props.resume_id, // 把 resume_id 发送给服务端
      })
    );
  };

  ws.onmessage = (event) => {
    try {
      const data = JSON.parse(event.data);

      if (data.interview_id) {
        uni.setStorageSync("current_interview_id", data.interview_id);
      } else if (data.context) {
        questions.value = [
          ...questions.value,
          {
            ...data,
            completed: false, // 默认未完成
          },
        ];
      }
    } catch (error) {
      console.error("消息解析失败:", error);
    }
  };
};

onMounted(() => {
  // 监听题目完成事件
  uni.$on("questionCompleted", onQuestionCompleted);
});

onUnmounted(() => {
  // 移除事件监听
  uni.$off("questionCompleted", onQuestionCompleted);
});

// 修改handleAnswer方法，传递事件通道
const handleAnswer = (question) => {
  const index = questions.value.findIndex((q) => q.id === question.id);
  if (index !== -1) {
    questions.value[index].completed = true;
  }
  uni.navigateTo({
    url: `/pages/index/index?interviewId=${uni.getStorageSync(
      "current_interview_id"
    )}&questionId=${question.id}&context=${encodeURIComponent(question.context)}&test=${
      question.test
    }`,
    events: {
      questionCompleted: (data) => {
        completedQuestions.value.add(data.questionId);
      },
    },
  });
};
</script>

<style scoped>
/* 新增题目列表样式 */
.questions-list {
  margin-top: 25px;
  display: grid;
  gap: 20px;
}

.question-card {
  border: 1px solid #ebeef5;
  border-radius: 8px;
  padding: 20px;
  background: #fafafa;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.question-content {
  flex: 1;
  margin-right: 20px;
}

/* 容器样式 */
.container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

/* 模块化设计 */
.section {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 20px;
  margin-bottom: 20px;
}

.section-title {
  color: #2c3e50;
  border-bottom: 2px solid #f0f0f0;
  padding-bottom: 10px;
  margin-bottom: 20px;
}

/* 输入框样式 */
.input-group {
  margin: 15px 0;
}

.vue-input {
  width: 100%;
  padding: 10px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  transition: border-color 0.3s;
}

.vue-input:focus {
  border-color: #409eff;
  outline: none;
}

/* 按钮样式 */
.vue-button {
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.primary {
  background-color: #409eff;
  color: white;
}

.primary:hover {
  background-color: #66b1ff;
}

.success {
  background-color: #67c23a;
  color: white;
}

.success:hover {
  background-color: #85ce61;
}

/* 题目卡片 */
.question-card {
  margin-top: 25px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  padding: 20px;
  background: #fafafa;
}

.question-title {
  color: #303133;
  margin-bottom: 15px;
}

.question-text {
  color: #606266;
  line-height: 1.6;
}

.question-meta {
  margin-top: 15px;
  display: flex;
  gap: 15px;
  color: #909399;
  font-size: 0.9em;
}

/* 新增已完成状态样式 */
.completed-status {
  color: #67c23a;
  font-weight: bold;
}

/* 已完成题目卡片样式 */
.question-card.completed {
  border-left: 4px solid #67c23a;
  background-color: #f0f9eb;
}

/* 禁用按钮样式 */
.vue-button[disabled] {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 题目卡片悬停效果 */
.question-card:not(.completed):hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
  transition: all 0.3s ease;
}

.submit {
  margin-top: 20px;
  background-color: #f56c6c;
  color: white;
}

.submit:hover {
  background-color: #f78989;
}
</style>
